<?php

namespace console\controllers;

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use yii\console\Controller;
use yii\console\widgets\Table;
use yii\helpers\Console;


class DemoController extends Controller
{

    /**
     * 命令行demo
     * @param $class
     * @throws \Exception
     */
    public function actionIndex($class)
    {

        if (Console::confirm("Are you sure?")) {
            Console::output("user input yes");
        }else{
            Console::output("user input no");
        }

        Console::prompt("你的名字",['required'=>true,'error'=>'必须输入']);



        $sex = Console::select("性别：",[1=>'男',2=>'女']);

        $formatSex = Console::ansiFormat($sex,[Console::FG_YELLOW]);
        Console::output("你的性别是：{$formatSex}");




        $name = Console::input("请输入你的名字：");

        $formatName = Console::ansiFormat($name,[Console::FG_YELLOW]);
        Console::output("你的名字是：{$formatName}");




        $hello = Console::ansiFormat("Hello",[Console::FG_YELLOW]);
        $world = Console::ansiFormat("World",[Console::FG_GREEN]);
        Console::output("{$hello} {$world}");

        $this->stdout("Hello?\n", Console::BOLD);
        echo Table::widget([
            'headers' => ['Project', 'Status', 'Participant'],
            'rows' => [
                ['Yii', 'OK', '@samdark'],
                ['Yii', 'OK', '@cebe'],
            ],
        ]);
        Console::startProgress(0,1000);
        for ($n=1;$n<1000;$n++){
            usleep(1000);
            Console::updateProgress($n,1000);
        }
        Console::endAnsiFormat();

    }

    /**
     * 监控一个进程是否执行
     */
    public function actionMonitorProcess(){
        $process = new Process("ps -fe|grep demo/process");
        $process->run();
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        echo PHP_EOL;
        // echo $process->getOutput();
        if(strpos($process->getOutput(),"/usr/bin/php /data/www/kit/yii demo/process") !== false){
            echo ':running';
            echo PHP_EOL;
        }else{
            echo ':start';
            echo PHP_EOL;
            echo '/usr/bin/php  /data/www/kit/yii demo/process';
            $process2 = new Process('/usr/bin/php  /data/www/kit/yii demo/process &');
            $process2->disableOutput();
            $process2->run();

            if (!$process2->isSuccessful()) {
                throw new ProcessFailedException($process2);
            }
        }
        echo PHP_EOL;
    }
}
